package com.ruoyi.system.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.dingutil.NetUtils;
import com.ruoyi.system.dingutil.YidaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class DingSer {
    public static final String JQ_APPKEY = "dingzamlgcjus7w8skye";
    public static final String JQ_APPSECRET = "5Ttg8yWHiREdK7spVcAWaKplf4qkn1SXblBkBvWmWYPS7tsnpC0_si2vfJhxtnVV";
    public static final String YD_APPKEY = "dingjjipn0epooepxypt";
    public static final String YD_APPSECRET = "8e_zm9coWiG71Zm1R0rUv4u0rE-eWPRif02mpNHR3b4SEVyjkNXyPl7L5gwUHzBu";
    private static final String ACCESS_TOKEN_URL_NEW = "https://oapi.dingtalk.com/gettoken?appkey=APPKEY&appsecret=APPSECRET";
    private static final String OTOMESSAGESBATCHSEND = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend";
    @Autowired
    RedisCache redisCache;
    @Value("${gasgpt.url}")
    private String gasgptUrl;
    @Value("${gasgpt.sign}")
    private String gasgptSign;

    /**
     * 获取令牌
     * @return
     */
    public String getDingToken(String prf,String appKey,String appsecret){
        String rediskey = prf+appKey;
        String cachetoken = redisCache.getCacheObject(rediskey);
        if(StringUtils.isNotEmpty(cachetoken)){
            return cachetoken;
        }else{
            String url = ACCESS_TOKEN_URL_NEW.replace("APPKEY", appKey).replace("APPSECRET", appsecret);
            String ret = NetUtils.get(url);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            if (jsonObject != null) {
                int errcode = jsonObject.getIntValue("errcode");
                if (errcode == 0) {
                    redisCache.expireObj(rediskey,jsonObject.getString("access_token"),70,TimeUnit.MINUTES);
                    return jsonObject.getString("access_token");
                }
            } else {
                return null;
            }
            return null;
        }
    }

    /**
     * 发送单聊消息
     * @return
     */
    public String sendoToMessages(String userIds,String msgKey,String msgParam){
        String xtoken = getDingToken("ROBOT#",JQ_APPKEY,JQ_APPSECRET);
        if(StringUtils.isEmpty(xtoken)){
            throw new RuntimeException("获取钉钉令牌为空");
        }
        JSONObject xdata = new JSONObject();
        xdata.put("robotCode",JQ_APPKEY);
        xdata.put("userIds", Arrays.asList(userIds));
        xdata.put("msgKey",msgKey);
        xdata.put("msgParam",msgParam);
        String cc =  NetUtils.postBodyyd(OTOMESSAGESBATCHSEND,xdata.toJSONString(),xtoken);
        System.out.println(cc);
        return cc;
    }
    public String gptChat(String uid,String msg){
        try{
            String url = this.gasgptUrl+"/chatbot";
            String sign = Md5Utils.hash(uid+this.gasgptSign);
            JSONObject xdata = new JSONObject();
            xdata.put("uid",uid);
            xdata.put("msg",msg);
            xdata.put("sign",sign);
            String rep = NetUtils.postBody(url,xdata.toJSONString());
            JSONObject repobj = JSON.parseObject(rep);
            return repobj.getString("content");
        }catch(Exception e){
            return "不好意思，暂时无法回答";
        }

    }
    public String yidaQueryForm(String key){
        String appType = "APP_E85W4SPPQXCAMW6LEMHF";
        String formUuid = "FORM-NO9667910B25RIU47ZNL87KJV8QU20AQ3UR9LN1";
        String currentPage = "1";
        String pageSize = "5";
        JSONArray sa = new JSONArray();
        JSONObject searchobj = new JSONObject();
        searchobj.put("key","textField_l9ru3ynf");
        searchobj.put("value",key);
        searchobj.put("type","TEXT");
        searchobj.put("operator","eq");
        searchobj.put("componentName","TextField");
        sa.add(searchobj);
        String searchFieldJson = sa.toJSONString();
        String systemToken = "2G766HA1F59TOBYUWSEAVUKAUJ1L1WYQW72TKT1";
        String userId = "xuykj";
        Map<String,String> ob = new HashMap<>();
        ob.put("appType",appType);
        ob.put("currentPage",currentPage);
        ob.put("pageSize",pageSize);
        ob.put("formUuid",formUuid);
        if(!org.springframework.util.StringUtils.isEmpty(searchFieldJson)) {
            ob.put("searchCondition", searchFieldJson);
        }
        else {
            ob.put("searchCondition", "{}");
        }
        ob.put("userId",userId);
        ob.put("systemToken",systemToken);
        String ss = JSON.toJSONString(ob);
        String xtoken = getDingToken("YIDA#",YD_APPKEY,YD_APPSECRET);
        JSONObject rr = YidaUtil.queryFormAdv(xtoken,ss);
        JSONArray datas = rr.getJSONArray("data");
        if(datas.size()>0){
            JSONObject one = datas.getJSONObject(0).getJSONObject("formData");
            String title = one.getString("textField_l9ru3yng");
            String content = one.getString("textareaField_l9ru3yno");
            JSONObject text = new JSONObject();
            text.put("content",content);
            return text.toJSONString();
        }else{
            JSONObject text = new JSONObject();
            text.put("content","未搜索到对应关键字");
            return text.toJSONString();
        }
    }
}
